<template>
  <el-dialog :visible.sync="visible"
             :title="!dataForm.id ? $t('add') : $t('update')"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             inline-message
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item prop="type"
                    :label="$t('menu.type')"
                    size="mini">
        <el-radio-group v-model="dataForm.type"
                        :disabled="!!dataForm.id">
          <el-radio :label="0">{{ $t('menu.type0') }}</el-radio>
          <el-radio :label="1">{{ $t('menu.type1') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="name"
                    :label="$t('menu.name')">
        <el-input v-model="dataForm.name"
                  :placeholder="$t('menu.name')"></el-input>
      </el-form-item>
      <el-form-item prop="parentName"
                    :label="$t('menu.parentName')"
                    class="menu-list">
        <el-popover v-model="menuListVisible"
                    ref="menuListPopover"
                    placement="bottom-start"
                    trigger="click">
          <el-tree :data="menuList"
                   :props="{ label: 'name', children: 'children', isLeaf: 'hasChildren' }"
                   node-key="id"
                   ref="menuListTree"
                   :highlight-current="true"
                   :expand-on-click-node="false"
                   accordion
                   lazy
                   :load="lazyLoadData"
                   @current-change="menuListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName"
                  v-popover:menuListPopover
                  :readonly="true"
                  :placeholder="$t('menu.parentName')">
          <i v-if="dataForm.pid !== '0'"
             slot="suffix"
             @click.stop="deptListTreeSetDefaultHandle()"
             class="el-icon-circle-close el-input__icon"></i>
        </el-input>
      </el-form-item>
      <el-form-item v-show="dataForm.type === 0"
                    prop="url"
                    :label="$t('menu.url')">
        <el-input v-model="dataForm.url"
                  :placeholder="$t('menu.url')"></el-input>
      </el-form-item>
      <el-form-item v-show="dataForm.type === 0"
                    prop="param"
                    :label="$t('menu.param')">
        <el-input v-model="dataForm.param"
                  :placeholder="$t('menu.param')"></el-input>
      </el-form-item>
      <el-form-item prop="sort"
                    :label="$t('menu.sort')">
        <el-input-number v-model="dataForm.sort"
                         controls-position="right"
                         size="small"
                         :min="0"
                         :label="$t('menu.sort')"></el-input-number>
      </el-form-item>
      <el-form-item prop="hideFromMenu"
                    :label="$t('menu.hideFromMenu')">
        <el-checkbox v-model="dataForm.hideFromMenu"
                     size="small"></el-checkbox>
      </el-form-item>
       <el-form-item prop="navMenu"
                    :label="$t('menu.showInNav')">
        <el-checkbox v-model="dataForm.navMenu"
                     size="small"></el-checkbox>
      </el-form-item>
      <el-form-item prop="permissions"
                    :label="$t('menu.permissions')">
        <el-input v-model="dataForm.permissions"
                  :placeholder="$t('menu.permissionsTips')"></el-input>
      </el-form-item>
      <el-form-item prop="tooltip"
                    :label="$t('menu.tooltip')">
        <div class="tooltipFormLablel">
          <!-- <label>Prompt information:</label> -->
          <el-input v-model="dataForm.tooltip.content" style="width:200px;margin-right:20px" :placeholder="$t('menu.tooltipFont')"></el-input>
          <label style="margin-right:5px">{{$t('statement.ht')}}</label>
          <el-checkbox v-model="dataForm.tooltip.hideTooltip" size="small"></el-checkbox>
          <!-- <input type="color" :value="dataForm.tooltip.color" /> -->
          <label style="margin-right:5px">{{$t('statement.fc')}}</label>
          <el-color-picker v-model="dataForm.tooltip.color" size="mini"></el-color-picker>
          <label style="margin-right:5px;margin-left:20px">{{$t('statement.bc')}}</label>
          <el-color-picker v-model="dataForm.tooltip.backGroundColor" size="mini"></el-color-picker>
        </div>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 0"
                    prop="icon"
                    :label="$t('menu.icon')"
                    class="icon-list">
        <el-popover v-model="iconListVisible"
                    ref="iconListPopover"
                    placement="bottom-start"
                    trigger="click"
                    popper-class="mod-sys__menu-icon-popover">
          <div class="mod-sys__menu-icon-inner">
            <div class="mod-sys__menu-icon-list">
              <el-button size="small"
                         v-for="(item, index) in iconList"
                         :key="index"
                         @click="iconListCurrentChangeHandle(item)"
                         :class="{ 'is-active': dataForm.icon === item }">
                <svg class="icon-svg"
                     aria-hidden="true">
                  <use :xlink:href="`#${item}`"></use>
                </svg>
              </el-button>
            </div>
          </div>
        </el-popover>
        <el-input v-model="dataForm.icon"
                  v-popover:iconListPopover
                  :readonly="true"
                  :placeholder="$t('menu.icon')"></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button size="small"
                 @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button size="small"
                 type="primary"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { debounce } from 'lodash'
import { getIconList } from '@/utils'
export default {
  data () {
    return {
      visible: false,
      menuList: [],
      menuListVisible: false,
      iconList: [],
      iconListVisible: false,
      dataForm: {
        id: '',
        type: 0,
        name: '',
        pid: '0',
        parentName: '',
        url: '',
        param: '',
        permissions: '',
        sort: 0,
        icon: 'icon-check-circle',
        tooltip: {
          hideTooltip: false,
          content: '',
          color: '#fff',
          backGroundColor: '#F56C6C'
        },
        hideFromMenu: false,
        navMenu: true
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        permissions: [
          { validator: this.validatePass, trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    'dataForm.type' (val) {
      this.$refs['dataForm'].clearValidate()
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm.permissions = ''
        this.iconList = getIconList()
        this.dataForm.parentName = this.$t('menu.parentNameDefault')
        this.getMenuList().then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }else{
            this.dataForm.tooltip={
              hideTooltip: false,
              content: '',
              color: '#fff',
              backGroundColor: '#F56C6C'
            }
          }
        })
      })
    },
    getMenuList (pid = 0, resolve) {
      return this.$interface.system.getMenuListWithLazyApi(pid)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let tempList = res.data
          for (let i = 0; i < tempList.length; i++) {
            tempList[i].hasChildren = !tempList[i].hasChildren
            if (tempList[i].type === 1) {
              tempList.splice(i, 1)
            }
          }
          if (pid === 0) {
            this.menuList = tempList
          } else {
            resolve(tempList)
          }
        }).catch(() => { })
    },
    getInfo () {
      this.$interface.system.getMenuInfoApi(this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (!res.data.tooltip||typeof res.data.tooltip!=='object') res.data.tooltip = this.dataForm.tooltip
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }
          if (this.dataForm.pid === '0') {
            return this.deptListTreeSetDefaultHandle()
          }
          this.$refs.menuListTree.setCurrentKey(this.dataForm.pid)
        }).catch(() => { })
    },
    deptListTreeSetDefaultHandle () {
      this.dataForm.pid = '0'
      this.dataForm.parentName = this.$t('menu.parentNameDefault')
    },
    menuListTreeCurrentChangeHandle (data) {
      this.dataForm.pid = data.id
      this.dataForm.parentName = data.name
      this.menuListVisible = false
    },
    iconListCurrentChangeHandle (icon) {
      this.dataForm.icon = icon
      this.iconListVisible = false
    },
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.dataForm.type === 0) {
          if (!this.dataForm.icon) {
            return this.$message.error('Please Select Icon')
          }
        }
        const changeSysMenu = () => {
          if (!this.dataForm.id) {
            return this.$interface.system.postSysMenu(this.dataForm)
          } else {
            return this.$interface.system.putSysMenu(this.dataForm)
          }
        }
        changeSysMenu().then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    lazyLoadData (node, resolve) {
      try {
        this.getMenuList(node.key, resolve)
      } catch (error) { }
    },
    validatePass (rule, value, callback) {
      if (this.dataForm.type === 1) {
        let Reg = /^sys:[A-Za-z:]+$/
        if (Reg.test(value)) {
          callback()
        } else {
          callback(new Error('Can only start with sys: and can only contain English and colons'))
        }
      } else {
          if (value === '0') {
            callback()
          } else {
            if (!value) {
            callback()
          } else {
            let Reg = /^sys:[A-Za-z:]+$/
            if (Reg.test(value)) {
              callback()
            } else {
              callback(new Error('Can only start with sys: and can only contain English and colons'))
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="scss">
.tooltipFormLablel{
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.mod-sys__menu {
  .menu-list,
  .icon-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }
  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}
</style>
